<template>
  <div class="questionList">
    <div class="searchBar">
      <el-select
        v-model="queryParam.tag"
        filterable
        placeholder="==请选择知识点=="
        clearable
        @change="findQuestion"
      >
        <el-option
          v-for="item in tags"
          :key="item.index"
          :label="item.name"
          :value="item.name"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="queryParam.type"
        placeholder="==请选择题型=="
        clearable
        @change="findQuestion"
      >
        <el-option
          v-for="item in questionType"
          :key="item.key"
          :value="item.key"
          :label="item.label"
        ></el-option>
      </el-select>
      <el-input
        v-model="queryParam.title"
        class="widthControl"
        clearable
        placeholder="请输入要查询的题目"
        @change="findQuestion"
      >
        <span slot="prefix" class="el-icon-search"></span>
      </el-input>
      <el-popover placement="bottom" trigger="click">
        <el-button
          icon="el-icon-edit"
          size="mini"
          v-for="item in questionType"
          :key="item.key"
          @click="$router.push({ path: item.url })"
          >{{ item.label }}
        </el-button>
        <el-button
          icon="el-icon-upload"
          round
          slot="reference"
          class="link-left btn"
          >添加题目</el-button
        >
      </el-popover>
    </div>

    <el-table
      v-loading="tableLoading"
      :data="tableData"
      fit
      highlight-current-row
      width="100%"
      stripe
    >
      <el-table-column prop="id" label="题目id" width="80" align="center">
      </el-table-column>
      <el-table-column prop="userId" label="创建人id" width="80" align="center">
      </el-table-column>
      <el-table-column prop="type" label="题型" width="70">
        <template v-slot="{ row }">
          <span>{{ questionType[row.type].label }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        align="center"
        label="题干"
        show-overflow-tooltip
      />
      <el-table-column
        sortable
        align="center"
        prop="level"
        label="难度"
        width="100px"
      >
        <template v-slot="{ row }">
          {{ levelChange(row.level) }}
        </template>
      </el-table-column>
      <el-table-column prop="tags" align="center" label="知识点" width="200">
        <template v-slot="{ row }">
          <el-tag
            v-for="item in row.tags"
            :key="item.index"
            @click="tagSearch(item.name)"
            >{{ item.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="600">
        <template slot-scope="{ row }">
          <el-button
            class="btn_primary"
            v-if="row.type == 2"
            icon="el-icon-document"
            size="mini"
            @click="showAnswer(row)"
            >参考答案</el-button
          >
          <el-button
            class="btn_success"
            v-if="row.type == 2"
            icon="el-icon-s-platform"
            size="mini"
            @click="textQuestion(row)"
            >测试</el-button
          >
          <el-button
            v-if="row.type == 2"
            class="btn_primary"
            size="mini"
            icon="el-icon-download"
            @click="downloadAttachment(row)"
            >下载用例</el-button
          >
          <el-button
            v-if="row.type == 2"
            class="btn_primary"
            size="mini"
            icon="el-icon-download"
            >备份</el-button
          >
          <el-button
            class="btn_primary"
            size="mini"
            icon="el-icon-view"
            @click="showQuestion(row)"
            >预览</el-button
          >
          <el-button
            class="btn_primary"
            size="mini"
            icon="el-icon-edit"
            @click="editQuestion(row)"
            :disabled="row.userId != userId && userId != 1"
            >编辑</el-button
          >
          <el-popconfirm
            icon="el-icon-info"
            icon-color="red"
            title="确定删除这个题目吗？"
            @confirm="() => deleteQuestion(row)"
          >
            <el-button
              class="btn_danger"
              slot="reference"
              size="mini"
              icon="el-icon-delete"
              :loading="row.removeLoading"
              :disabled="row.userId != userId && userId != 1"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParam.pageNum"
      :page-sizes="[5, 10, 20, 30, 50]"
      :page-size="queryParam.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalSize"
    >
    </el-pagination>
    <el-dialog
      :visible.sync="questionShow.dialog"
      v-if="questionShow.question"
      style="width: 100%;height: 100%"
    >
      <div v-if="questionShow.question.type == 2">
        <program-detail :question="questionShow.question"></program-detail>
      </div>
      <div v-else style="text-align:left;padding-bottom:20px">
        <choice-detail :question="questionShow.question"></choice-detail>
      </div>
    </el-dialog>
    <!--参考答案-->
    <el-dialog
      class="answer"
      title="参考答案"
      :visible.sync="dialogVisible"
      append-to-body
    >
      <codeHeightLight :sourceCode="form.answer" />
      <div slot="footer">
        <el-button
          class="btn_primary"
          type="primary"
          @click.native="dialogVisible = false"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllTag,
  getAllQuestion,
  deletePGProblem,
  deleteSLProblem,
  downloadAttachment
} from "@/api/question.js";
import programDetail from "@/components/programDetail.vue";
import choiceDetail from "@/components/choiceDetail.vue";
import codeHeightLight from "@/components/codeHighlight.vue";
export default {
  components: {
    programDetail,
    choiceDetail,
    codeHeightLight
  },
  data() {
    return {
      answer: "",
      form: {},
      dialogVisible: false,
      queryParam: {
        title: null,
        tag: null,
        type: null,
        pageNum: 1,
        pageSize: 10
      },
      userId: null,
      roleName: "teacher",
      totalSize: 10,
      tags: [],
      questionType: [
        {
          key: 0,
          url: "choiceCreate",
          label: "选择题"
        },
        {
          key: 1,
          url: "judgeCreate",
          label: "判断题"
        },
        {
          key: 2,
          url: "programCreate",
          label: "程序题"
        }
      ],
      tableLoading: false,
      tableData: [],
      questionShow: {
        dialog: false,
        question: null
      }
    };
  },
  created() {
    this.userId = JSON.parse(localStorage.getItem("user")).userId; //获取当前用户ID  //若非出题人或超管不能编辑题目
    this.roleName = JSON.parse(localStorage.getItem("user")).roleName;
    this.getTableData();
    getAllTag().then(res => {
      this.tags = res;
    });
  },
  computed: {
    levelChange() {
      let levels = ["easy", "medium", "hard", "insuperable", "hell"];
      return val => {
        return levels[val];
      };
    }
  },
  activated() {
    this.getTableData();
  },
  methods: {
    // 下载测试用例
    downloadAttachment(row) {
      downloadAttachment({ testCaseId: row.testCaseId })
        .then(res => {
          console.log(res);
          // 根据文件流下载测试用例
          var blob = new Blob([res], {
            type: "application/zip;charset-UTF-8"
          });

          const blobUrl = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = blobUrl;
          a.download = "testCase.zip";
          a.click();
          URL.revokeObjectURL(blobUrl); // 释放内存
          this.$message.success("请求成功");
        })
        .catch(err => {
          this.$message.error("请求失败");
        });
    },
    //点击表格知识点时，自动搜索知识点
    tagSearch(name) {
      this.queryParam.tag = name;
      this.findQuestion();
    },
    findQuestion() {
      this.queryParam.pageNum = 1;
      this.getTableData();
    },
    getTableData() {
      this.tableLoading = true;
      getAllQuestion(this.queryParam)
        .then(res => {
          res.data.forEach(element => {
            element.removeLoading = false;
            if (element.type == undefined) element.type = 2;
          });
          this.tableData = res.data;
          this.totalSize = res.total;
        })
        .catch(err => {
          this.tableData = [];
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    showQuestion(row) {
      this.questionShow.dialog = true;
      this.questionShow.question = row;
    },
    handleSizeChange(size) {
      this.queryParam.pageSize = size;
      this.getTableData();
    },
    handleCurrentChange(page) {
      this.queryParam.pageNum = page;
      this.getTableData();
    },
    deleteQuestion(row) {
      row.removeLoading = true;
      if (row.type == 2) {
        deletePGProblem(row.id)
          .then(res => {
            this.$message.success("删除成功");
          })
          .finally(() => {
            row.removeLoading = false;
            this.getTableData();
          });
        return;
      }
      deleteSLProblem(row.id)
        .then(res => {
          this.$message.success("删除成功");
        })
        .finally(() => {
          row.removeLoading = false;
          this.getTableData();
        });
    },
    editQuestion(row) {
      //console.log(row)
      if (row.type == 0) {
        this.$router.push({
          name: "questionModule/choiceCreate",
          query: { id: row.id },
          params: { data: row }
        });
      } else if (row.type == 1) {
        this.$router.push({
          name: "questionModule/judgeCreate",
          query: { id: row.id },
          params: { data: row }
        });
      } else {
        this.$router.push({
          name: "questionModule/programCreate",
          query: { id: row.id },
          params: { data: row }
        });
      }
    },
    textQuestion(row) {
      row.examAndExperimentId=0;
      this.$router.push({
        name: "experimentModule/experimentDetail",
        params: { data: row }
      });
    },
    showAnswer(row) {
      this.dialogVisible = true;
      this.form = row;
      if (!this.form.answer) {
        this.form.answer = "// 暂无答案";
      }
      this.answer = row.answer;
      console.log(row);
    }
    // editAnswer() {
    //   if (this.form.answer !== this.answer) {
    //     delete this.form.removeLoading;
    //     delete this.form.type;
    //     editPGProblem(this.form)
    //       .then(res => {
    //         if (!this.answer) {
    //           this.$message.success("参考答案上传成功！");
    //         } else {
    //           this.$message.success("参考答案修改成功！");
    //         }
    //       })
    //       .catch(err => {
    //         this.$message.error("参考答案上传或编辑失败！");
    //       });
    //   }
    //   this.dialogVisible = false;
    // }
  }
};
</script>
<style lang="scss" scoped>
.el-form--inline {
  height: 58px;
  box-sizing: border-box;
}
.el-form--inline .el-form-item__label {
  font-size: 14px;
  padding: 0px;
  font-weight: bold !important;
}
.el-table__row {
  height: 43px !important;
}
.el-pagination {
  margin-top: 20px;
  margin-left: 30px;
}
.el-tag {
  margin-right: 5px;
}
.el-tag:hover {
  background-color: #3b77e3;
  color: white;
  cursor: pointer;
}
.searchBar {
  display: flex;
  flex-direction: row;
  position: relative;
  margin-bottom: 10px;
  .el-select {
    height: 30px;
    margin-right: 20px;
  }
  /deep/ .el-input__inner {
    height: 30px;
    line-height: 30px;
    border-radius: 20px !important;
  }
  /deep/ .el-input__icon {
    line-height: 30px;
  }
  .el-icon-search {
    line-height: 30px;
    padding-left: 8px;
    color: #5b8bff;
    font-weight: bold;
  }
  .widthControl {
    width: 300px;
  }
  .btn {
    background: #5b8bff;
    color: #f4f4f5;
    position: absolute;
    right: 50px;
    height: 30px !important;
    line-height: 30px;
    width: 100px;
    padding: 0;
  }
}
.el-table {
  .el-button {
    margin: 0;
    border: 0;
    background: initial;
  }
  .el-button:hover {
    background: #5b8bff;
    color: #f4f4f5;
  }
}
</style>
